package adventure.commands.admin;

import adventure.*;
import adventure.commands.*;
import colour.ColourUtil;
import player.*;

/**
 *
 * @author Michael Hanns
 *
 */
public class ChangeName extends AbstractCommand {

    public ChangeName(Adventure a) {
        super(a, new String[]{"CHANGENAME"});
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if (p.isAdmin()) {
            if (args.length == 3) {
                return changeName(args[1], args[2]);
            } else {
                return "Change who's name to what?\nSyntax: changename <target player> <new name>";
            }
        } else {
            return "Command not recognised.";
        }
    }
    
    private String changeName(String target, String newName) {
        if (newName.length() < 3 || newName.length() > 12) {
            return "Invalid name! New name must be between 3 and 12 characters long.";
        } else if (newName.contains(" ")) {
            return "Invalid name! You may not include spaces in your name.";
        }

        Player targetPlayer = players.getOnlinePlayer(target);
        
        if(targetPlayer.getID() > 0) {
            newName = newName.substring(0,1).toUpperCase()
                    + newName.substring(1).toLowerCase();
            
            if((players.getOnlinePlayer(newName).getID() > 0)
                    || (players.getOfflinePlayer(newName).getID() > 0)) {
                return "A player by that name already exists!";
            }
            
            String oldName = targetPlayer.getAliveName();
            ((PlayerEdit)targetPlayer).setName(newName);
            
            players.savePlayers();
            
            out.broadcastToPlayer(targetPlayer, "You have been renamed to "
                    + ColourUtil.colourise(newName, ColourUtil.player)
                    + ".");
            
            return ColourUtil.colourise(oldName, ColourUtil.player)
                    + " has been renamed to "
                    + ColourUtil.colourise(newName, ColourUtil.player)
                    + ".";
        } else {
            targetPlayer = players.getOfflinePlayer(target);
            
            if(targetPlayer.getID() > 0) {
                return "Player "
                     + ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player)
                     + " must be online to change their name.";
            }
        }
        return "Player " + target + " does not exist!";
    }

    
}
